package com.course.controller;

import com.course.entity.Employees;
import com.course.repository.EmployeesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/employees")
public class EmployeesHandler {
    @Autowired
    private EmployeesRepository employeesRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Employees> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return employeesRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody Employees employees) {
        Employees result = employeesRepository.save(employees);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @GetMapping("findById/{id}")
    public Employees findById(@PathVariable("id") Integer id) {
        Employees employees = employeesRepository.findById(id).get();
        return employees;
    }

    @PutMapping("/edit")
    public String edit(@RequestBody Employees employees) {
        Employees result = employeesRepository.save(employees);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @DeleteMapping("/del/{id}")
    public void del(@PathVariable("id") Integer id) {
        employeesRepository.deleteById(id);
    }
}
